package com.silence.whereeat;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings.System;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;

public class TakePicActivity extends Activity {
	
	SurfaceView surface;
	Button takebtn;
	Camera camera;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.setContentView(R.layout.takepic);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		surface=(SurfaceView) findViewById(R.id.picsurface);
		takebtn=(Button) findViewById(R.id.takepicbtn);
		SurfaceHolder holder=surface.getHolder();
		holder.setKeepScreenOn(true);
		holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		holder.addCallback(new Mycallback());
		takebtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				camera.takePicture(null, null,new MyJpegCallback() );
				
			}
		});
		
		
	}
	
	
	class MyJpegCallback implements PictureCallback
	{

		@Override
		public void onPictureTaken(byte[] buffer, Camera arg1) {
			
			try {
				File f=new File(Environment.getExternalStorageDirectory(),java.lang.System.currentTimeMillis()+".jpeg");
				FileOutputStream fos=new FileOutputStream(f);
				fos.write(buffer);
				camera.startPreview();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	
	class Mycallback implements Callback{

		@Override
		public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2,
				int arg3) {
			
		}

		@Override
		public void surfaceCreated(SurfaceHolder arg0) {
			try {
				camera=Camera.open();
				Parameters param=camera.getParameters();
				param.setPictureSize(1024, 768);
				param.setJpegQuality(85);
				param.setPreviewFrameRate(5);
				//camera.setParameters(param);
				camera.setPreviewDisplay(surface.getHolder());
				camera.startPreview();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			
			
		}

		@Override
		public void surfaceDestroyed(SurfaceHolder arg0) {
			if(camera!=null)
			{
				camera.release();
				camera=null;
			}
			
		}
		
		
	}

}
